react-native-maps 表示範囲から最大(最小)の緯度経度を算出する
#reactnative
背景・前提
react-native-mapsでは、現在表示してる地図の範囲をRegionと呼んでる。
このRegion は4つのプロパティを持っている。
table:region
名前 説明
latitude 表示範囲の中心緯度
longitude 表示範囲の中心経度
latitudeDelta 表示範囲の緯度の長さ
longitude 表示範囲の経度の長さ
この4つのデータを用いて、表示範囲の最大(最小)の緯度/経度を算出する方法を知りたい
シンプルな算出方法は「latitude(longitude)とlatitudeDelta(longitudeDelta)を足し引きする」
hr.icon
シンプルに考えればすぐわかるやり方。ただ、Googleが提供してる仕様の説明からすると、これは正確でない状況もあり得るっぽい。(詳細は説明しないが...)
code: sample.js
getBounds = region => {
let west = region.longitude - region.longitudeDelta / 2;
let south = region.latitude - region.latitudeDelta / 2;
let east = region.longitude + region.longitudeDelta / 2;
let north = region.latitude + region.latitudeDelta / 2;
// do something
}
少し正確性を求めた方法
hr.icon
コードの詳細をちゃんと読んでないが、シンプルなものよりコードが長くなってる
Get current bounding box (north-east/south-west coordinates) · Issue #356 · react-native-maps/react-native-maps · GitHub
code: sample.js
export const getBoundByRegion = (region, scale = 1) => {
/*
* Latitude : max/min +90 to -90
* Longitude : max/min +180 to -180
*/
// Of course we can do it mo compact but it wait is more obvious
const calcMinLatByOffset = (lng, offset) => {
const factValue = lng - offset;
if (factValue < -90) {
return (90 + offset) * -1;
}
return factValue;
};
const calcMaxLatByOffset = (lng, offset) => {
const factValue = lng + offset;
if (90 < factValue) {
return (90 - offset) * -1;
}
return factValue;
};
const calcMinLngByOffset = (lng, offset) => {
const factValue = lng - offset;
if (factValue < -180) {
return (180 + offset) * -1;
}
return factValue;
};
const calcMaxLngByOffset = (lng, offset) => {
const factValue = lng + offset;
if (180 < factValue) {
return (180 - offset) * -1;
}
return factValue;
};
const latOffset = region.latitudeDelta / 2 * scale;
const lngD = (region.longitudeDelta < -180) ? 360 + region.longitudeDelta : region.longitudeDelta;
const lngOffset = lngD / 2 * scale;
return {
minLng: calcMinLngByOffset(region.longitude, lngOffset), // westLng - min lng
minLat: calcMinLatByOffset(region.latitude, latOffset), // southLat - min lat
maxLng: calcMaxLngByOffset(region.longitude, lngOffset), // eastLng - max lng
maxLat: calcMaxLatByOffset(region.latitude, latOffset),// northLat - max lat
}
}
参考
Get current location, latitude and longitude in ReactNative using react-native-maps - Stack Overflow
Get current bounding box (north-east/south-west coordinates) · Issue #356 · react-native-maps/react-native-maps · GitHub